package cn.ven.controller;

import cn.ven.entity.Blog;
import cn.ven.entity.Largefile;
import cn.ven.entity.MyUser;
import cn.ven.entity.UserTagBlogContent;
import cn.ven.service.BlogService;
import cn.ven.service.LargeFileService;
import cn.ven.service.TagService;
import cn.ven.service.UserService;
import cn.ven.tool.RespJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/*
pubic 为公共部分，管理员以及用户都有权限
功能如下:
1./user/**   注册用户，根据用户id查找用户
2./tag/findAll  查找所有的标签
3./blog/**   根据id查看博客内容，查看所有closed==1的博客，查看一次博客内容，游览量+1
 */


@Controller
@RequestMapping("/api/public")
@CrossOrigin
public class PublicController {
    private Logger logger =LoggerFactory.getLogger(PublicController.class);

    @Autowired
    UserService userService;

    @Autowired
    LargeFileService largeFileService;

    @Autowired
    TagService tagService;

    @Autowired
    BlogService blogService;


    //注册用户
    @RequestMapping("/user/addUser")
    @ResponseBody
    public Map<String,Object> addUser(MyUser user,
                                      @RequestParam("pic")MultipartFile file)throws Exception{
        if (userService.findByUsername(user.getUsername())==null){
            Largefile largefile =new Largefile();
            if (file!=null&&file.getSize()>0){//判断是否已经有了图片，如果有就更新
                largefile.setFilename(file.getOriginalFilename());//获取文件原名
                logger.info("originFilename====="+file.getOriginalFilename());
                byte[] bytes = file.getBytes();
                largefile.setContent(bytes);
                String newName =UUID.randomUUID().toString();//获取唯一名
                largefile.setId(newName);
                logger.info("lagrefile==="+largefile);
                largeFileService.addLargefile(largefile);
            }
            user.setPicture(largefile.getId());
            userService.addUser(user);
            return RespJson.pack(200,"添加成功",user);
        }
           return RespJson.pack(500,"添加失败，该用户已经存在了","");
    }

    //根据用户id查找用户
    @RequestMapping("/user/findUserById/{id}")
    @ResponseBody
    public Map<String,Object> findUserById(@PathVariable("id")Integer id){
        MyUser user = userService.findById(id);
        return RespJson.pack(200,"",user);
    }

    //查找所有的tag
    @RequestMapping("/tag/findAll")
    @ResponseBody
    public Map<String,Object> findAll(){
        return RespJson.pack(200,"",tagService.findAll());
    }

    //根据博客id查找相关博客信息
    @RequestMapping("/blog/findUserTagBlogContent/{blogid}")
    @ResponseBody
    public Map<String,Object> findUserTagBlogContent(@PathVariable("blogid")Integer blogid){
        UserTagBlogContent userTagBlogContent = blogService.findUserTagBlogContent(blogid);
       return RespJson.pack(200,"",userTagBlogContent);
    }

    //查找没有假删除博客
    @RequestMapping("/blog/showBlogs")
    public Map<String,Object> showBlogs(){
        List<UserTagBlogContent> userTagBlogContents = blogService.findBlogByClosed(1);
        return RespJson.pack(200,"",userTagBlogContents);
    }

    //查看图片
    @RequestMapping("/show/{id}")
    public  void show(HttpServletResponse response,
                      @PathVariable("id") String id){  //图片的uuid
        if (id==null)//判断书是否为空或者图片是否为空
            return;
        try {
            Largefile largeFile = largeFileService.findById(id);//根据uuid查找文件
            byte[] buf=(byte[]) largeFile.getContent();//向下转型
            response.setContentType("image/jpeg");//设置图片的格式
            FileCopyUtils.copy(buf, response.getOutputStream()); //复制到网页进行输出
        }catch (Exception e){
            System.err.println(e);
        }
    }


}
